package com.unipay.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unipay.common.result.Result;
import com.unipay.model.system.SysRole;
import com.unipay.model.vo.AssginRoleVo;
import com.unipay.model.vo.SysRoleQueryVo;
import com.unipay.system.handler.UnipayException;
import com.unipay.system.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: unipay-auth-parent
 * @Author: cmy
 * @CreateTime: 2023-02-01  21:31
 * @Description:
 *      TODO
 *          （1）controller调用service
 *          （2）service调用mapper
 *          （3）mapper中创建方法
 *          （4）mapper.xml配置文件中，编写 “动态SQL”
 *
 *      测试接口地址：
 *          3、分页查询---http://localhost:8800/doc.html#/adminApi/%E8%A7%92%E8%89%B2%E7%AE%A1%E7%90%86/pageSelUsingGET
 */
@Api(tags = "角色管理")
@RequestMapping("/admin/system/sysRole")    // 接口部分路径
@RestController     // @Controller + @ResponseBody
public class SysRoleController {

    // TODO 注入service
    @Autowired
    private SysRoleService sysRoleService;

    /*
     * TODO 8、给用户分配角色
     *  #### 接口分析
     * 1、进入分配页面：获取已分配角色与全部角色，进行页面展示
     * 2、保存分配角色：删除之前分配的角色和保存现在分配的角色
     **/
    @ApiOperation(value = "ID获取用户角色")
    @GetMapping("/toAssign/{userId}")
    public Result toAssign(@PathVariable("userId") Long userId){
        Map<String, Object> roleMap = sysRoleService.getRolesByUserId(userId);
        return Result.ok(roleMap);
    }
    @ApiOperation(value = "根据用户分配角色")
    @PostMapping("/doAssign")
    public Result doAssign(@RequestBody AssginRoleVo assginRoleVo){
        sysRoleService.doAssign(assginRoleVo);
        return Result.ok();
    }


    // 7、批量删除角色
    @ApiOperation(value = "批量删除角色")
    @DeleteMapping("/batchRemove")
    public Result batchRemove(@RequestBody List<Long> idList){
        boolean b = sysRoleService.removeByIds(idList);
        if (b){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
    // 6、修改角色   ---TODO 和“新增”的区别：必须有 ID，通过前端传递
    @ApiOperation(value = "修改角色")
    @PutMapping("/update")
    public Result update(@RequestBody SysRole sysRole){
        boolean b = sysRoleService.updateById(sysRole);
        if (b){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
    // 5、新增角色
    @ApiOperation(value = "新增角色")
    @PostMapping("/save")
    public Result save(@RequestBody SysRole sysRole){
        boolean save = sysRoleService.save(sysRole);
        System.out.println("--------" + save);
        if (save){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
    // 4、根据ID获取角色
    @ApiOperation(value = "根据ID获取角色")
    @GetMapping("/get/{id}")
    public Result getById(@PathVariable("id") Long id){
        SysRole sysRole = sysRoleService.getById(id);
        System.out.println(sysRole);
        if (sysRole == null){
            return Result.fail();
        }else {
            return Result.ok(sysRole);
        }
    }


    // 3、分页查询
    @ApiOperation(value = "分页条件查询")
    @GetMapping("/{page}/{limit}")
    public Result pageSel(
            @PathVariable("page") Long page,
            @PathVariable("limit") long limit,
            SysRoleQueryVo sysRoleQueryVo){         // TODO “条件”传参
        //（1）创建page对象
        Page<SysRole> pageParam = new Page<>(page, limit);
        //（2）调用service方法
        IPage<SysRole> pageModel = sysRoleService.selPage(pageParam, sysRoleQueryVo);   // pageModel有许多方法...读到pages、total、current等
        //（3）返回结果
        return Result.ok(pageModel);
    }

    // 2、删除：逻辑接口
    @ApiOperation(value = "根据ID删除角色")
    @DeleteMapping("/del/{id}")
    private Result del(@PathVariable("id") Long id){
        boolean b = sysRoleService.removeById(id);
//        System.out.println(b);
        if (b){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    // 1、查询所有记录
    @ApiOperation(value = "获取全部角色")
    @GetMapping("/getAll")
    public Result<List<SysRole>> getAll(){
        /*
         * @description: 测试异常处理
         **/
        try {
//            int i = 9 / 0;
            int i = 9 / 1;
        } catch (Exception e) {
//            e.printStackTrace();
            throw new UnipayException(222, "自定义处理异常！！！");
        }
        List<SysRole> list = sysRoleService.list();
//        return list;
        return Result.ok(list);
        /*
         * @description:
         *      http://localhost:8800/admin/system/sysRole/getAll返回，JSON数组格式数据：
         * [
         *  {"id":"1","createTime":"2021-05-31T10:09:18.000+00:00","updateTime":"2022-06-08T01:21:10.000+00:00","isDeleted":0,"param":{},"roleName":"系统管理员","roleCode":"SYSTEM","description":"系统管理员"},
         *  {"id":"8","createTime":"2022-06-08T09:39:04.000+00:00","updateTime":"2022-06-08T09:39:04.000+00:00","isDeleted":0,"param":{},"roleName":"用户管理员","roleCode":"yhgly","description":null},
         *  ...
         * ]
         **/
    }
}
